package awake.stu.dbhb;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;


public class ViewPanel extends JPanel {

    private static String IMAGES_PATH = "E:/for_db/";
    private static String DEFAULT_IMAGE = "E:/for_db/Pedobearseal.jpg";
    private static int NOT_FOUND_INDEX = -1;

    private ImagePanel imagePanel;
    private ArrayList<Person> persons = new ArrayList<Person>();
    private JTable table;
    private TextArea description;

    private JPanel buttonPanel;
    private JButton connButton;
    private JButton updateButton;
    private JButton addButton;
    private JButton deleteButton;
    private JButton addPicture;
    private JButton importFile;
    private JButton exportFile;
    private DateTableCellEditor dateTableCellEditor;
    MyModel tableModel;

    private JFileChooser fileChooser;

    public ViewPanel() {
        tableModel = new MyModel(persons);
        table = new JTable(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(700, 300));
        table.setFillsViewportHeight(true);
        imagePanel = new ImagePanel();
        imagePanel.setPreferredSize(new Dimension(300, 300));

        JScrollPane sclPane = new JScrollPane(table);
        add(sclPane, BorderLayout.CENTER);

        ListSelectionModel rowSelectionModel = table.getSelectionModel();
        rowSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        rowSelectionModel.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (table.getSelectedRow() >= 0) {
                    showImage(persons.get(table.getSelectedRow()).getImgName());
                    description.setText(persons.get(table.getSelectedRow()).getDescription());
                    description.setEditable(true);
                    importFile.setEnabled(true);
                    exportFile.setEnabled(true);
                    addPicture.setEnabled(true);
                }
            }
        });

        showImage(null);

        description = new TextArea();
        description.setEditable(false);
        description.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (table.getSelectedRow() != NOT_FOUND_INDEX) {
                    persons.get(table.getSelectedRow()).setDescription(description.getText());
                }
            }
        });

        add(description, BorderLayout.SOUTH);

        buttonPanel = new JPanel();
        add(buttonPanel, BorderLayout.SOUTH);

        connButton = new JButton("Connect Database");
        updateButton = new JButton("Update Database");
        addButton = new JButton("Add Person");
        deleteButton = new JButton("Delete Person");
        importFile = new JButton("Import File");
        exportFile = new JButton("Export File");
        addPicture = new JButton("Select Picture");
        importFile.setEnabled(false);
        exportFile.setEnabled(false);
        addPicture.setEnabled(false);

        buttonPanel.add(connButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(importFile);
        buttonPanel.add(exportFile);
        buttonPanel.add(addPicture);

        connButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fillTable();
            }
        });

        updateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                updateDB();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                deletePerson();
            }
        });

        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addPerson();
            }
        });

        importFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("."));
                int result = fileChooser.showOpenDialog(ViewPanel.this);

                if (result == JFileChooser.APPROVE_OPTION) {
                    File newFile = new File(IMAGES_PATH + fileChooser.getSelectedFile().getName());

                    try {
                        copyFile(fileChooser.getSelectedFile(), newFile);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                    persons.get(table.getSelectedRow()).setFileName(newFile.getPath());
                    repaint();
                }
            }
        });

        exportFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser = new JFileChooser();
                fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
                fileChooser.setSelectedFile(new File(persons.get(table.getSelectedRow()).getFileName()));

                int result = fileChooser.showSaveDialog(ViewPanel.this);

                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        copyFile(new File(persons.get(table.getSelectedRow()).getFileName()), fileChooser.getSelectedFile());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        addPicture.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("."));
                FileNameExtensionFilter fileFilter = new FileNameExtensionFilter("JPG files", "jpg");
                fileChooser.setFileFilter(fileFilter);
                fileChooser.setAccessory(new ImagePreviewer(fileChooser));
                int result = fileChooser.showOpenDialog(ViewPanel.this);

                if (result == JFileChooser.APPROVE_OPTION) {
                    File newPicture = new File(IMAGES_PATH + fileChooser.getSelectedFile().getName());

                    try {
                        copyFile(fileChooser.getSelectedFile(), newPicture);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                    showImage(newPicture.getPath());
                    persons.get(table.getSelectedRow()).setImgName(newPicture.getPath());
                }
            }
        });
    }

    private void copyFile(File in, File out) throws Exception {
        FileInputStream fis = new FileInputStream(in);
        FileOutputStream fos = new FileOutputStream(out);
        byte[] buf = new byte[1024];
        int i = 0;

        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }

        fis.close();
        fos.close();
    }

    private void showImage(String imgLink) {
        BufferedImage img;

        try {
            img = ImageIO.read(new File(imgLink != null && !imgLink.isEmpty() ? imgLink : DEFAULT_IMAGE));
            imagePanel.setImage(img);
            add(imagePanel, BorderLayout.EAST);
            imagePanel.setVisible(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void fillTable() {
        persons.clear();
        PersonDao p = new PersonDao();

        try {
            p.getAllPersons(persons);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        tableModel.fireTableStructureChanged();
        tableModel.fireTableDataChanged();
    }

    private void updateDB() {
        PersonDao pd = new PersonDao();

        for (Person p : persons) {
            try {
                pd.updatePerson(p.getPerson_id(), p);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void deletePerson() {
        PersonDao pd = new PersonDao();

        try {
            if (table.getSelectedRow() >= 0) {
                pd.deletePerson(persons.get(table.getSelectedRow()));
                persons.remove(persons.get(table.getSelectedRow()));
                tableModel.fireTableStructureChanged();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void addPerson() {
        PersonDao pd = new PersonDao();

        try {
            Person newPers = new Person();
            persons.add(newPers);
            pd.addPerson(newPers);
            tableModel.fireTableStructureChanged();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}


